﻿using Heroius.Extension;
using EnvSafe.Open.EPE.Vent;
using GB15605_2008 = EnvSafe.Open.EPE.Vent.GB15605_2008;
using GB15605_2017 = EnvSafe.Open.EPE.Vent.GB15605_2017;
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using System.Diagnostics;

namespace EnvSafe.Open.EPE
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            App.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            InitializeComponent();
            //添加预定义进料枚举描述
            EnumShell<object>.Descriptions.Add(EPE.VentDesign.FeedingWay.FreeFalling, "自由落体");
            EnumShell<object>.Descriptions.Add(EPE.VentDesign.FeedingWay.None, "无");
            EnumShell<object>.Descriptions.Add(EPE.VentDesign.FeedingWay.PneumaticAxial, "轴向中心进料");
            EnumShell<object>.Descriptions.Add(EPE.VentDesign.FeedingWay.PneumaticTangential, "切向进料");
            //dialog
            diaopen = new OpenFileDialog();
            diaopen.Filter = "泄爆计算配置|*.rplx";
            diasave = new SaveFileDialog();
            diasave.Filter = "泄爆计算配置|*.rplx";

            TbVer.Text = $"版本 {App.Version}";

            DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public Properties.Settings Settings { get { return Properties.Settings.Default; } }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            Settings.Save();
        }

        #region 上下文实体

        public GB15605_2008.ContainerEntity container { get; set; } = new GB15605_2008.ContainerEntity();
        public GB15605_2008.PipeEntity pipe { get; set; } = new GB15605_2008.PipeEntity();
        public GB15605_2008.BuildingEntity building { get; set; } = new GB15605_2008.BuildingEntity();
        public GB15605_2008.SystemEntity system { get; set; } = new GB15605_2008.SystemEntity();

        public GB15605_2017.PipeEntity pipe17 { get; set; } = new GB15605_2017.PipeEntity();
        public GB15605_2017.BuildingEntity building17 { get; set; } = new GB15605_2017.BuildingEntity();

        #endregion

        #region 日志

        public ObservableCollection<string> Logs { get; set; } = new ObservableCollection<string>();

        private void CopyLogItem_Click(object sender, RoutedEventArgs e)
        {
            var str = (sender as FrameworkElement).DataContext as string;
            Clipboard.SetText(str);
        }

        private void ClearLog_Click(object sender, RoutedEventArgs e)
        {
            Logs.Clear();
        }

        #endregion

        CalcResult latestResult;

        private void Calculate_Click(object sender, RoutedEventArgs e)
        {
            var ti = TabInput.SelectedItem as TabItem;
            var tag = ti.Tag.ToString();
            var en = (ti.Content as FrameworkElement).DataContext as Entity;

            var context = en.GenProperContext();

            context.ObjectEntity = en;
            latestResult = context.Calculate();

            foreach (var item in latestResult.Remarks)
            {
                Logs.Add(item);
            }

            string result;
            if (latestResult.Succeed)
            {
                //处理特殊的结果格式化
                switch (tag)
                {
                    case "S08":
                        result = $"求得泄压面积，按A-管道-B排列（㎡）: { latestResult.Results.Select(d => d.As<string>()).Merge(" , ") }";
                        break;
                    case "P17":
                        result = $"求得泄爆间隔距离（m）：{ latestResult.Results[0] }";
                        break;
                    default:
                        result = $"求得泄压面积（㎡）: { latestResult.Results.Select(d => d.As<string>()).Merge(" , ") }";
                        break;
                }
                Clipboard.SetText(result);
            }
            else
            {
                result = "计算失败";
            }
            Logs.Add(result);
            MessageBox.Show(result);

            // roll to bottom
            ScrollLog.ScrollToBottom();
        }

        #region IO

        OpenFileDialog diaopen;
        private void Import_Click(object sender, RoutedEventArgs e)
        {
            if (diaopen.ShowDialog() == true)
            {
                //read from file
                var stream = diaopen.OpenFile();
                XDocument xdoc = XDocument.Load(stream);
                var root = xdoc.Descendants("VentCalc").First();
                string tag = root.Attribute("tab")?.Value;

                //兼容性修正
                switch (tag)
                {
                    case "0": tag = "C08"; break;
                    case "1": tag = "B08"; break;
                    case "2": tag = "P08"; break;
                    case "3": tag = "S08"; break;
                }

                var ti = TabInput.Items.Cast<TabItem>().First(t => (t as TabItem).Tag.ToString() == tag);
                TabInput.SelectedItem = ti;
                var en = (ti.Content as FrameworkElement).DataContext as Entity;
                en.ReadXml(root.Elements().First());
                en.RaiseAllPropertiesChangedEvent();

                stream.Close();
            }
        }

        SaveFileDialog diasave;

        private void Export_Click(object sender, RoutedEventArgs e)
        {
            if (diasave.ShowDialog() == true)
            {
                var ti = TabInput.SelectedItem as TabItem;
                var tag = ti.Tag.ToString();
                var en = (ti.Content as FrameworkElement).DataContext as Entity;

                var sw = new StreamWriter(diasave.OpenFile());
                sw.Write($"<!--Generated by VentCalculator, {DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")}-->");
                sw.Write($"<VentCalc version=\"{App.Version}\" tab=\"{tag}\"><Target>{en.GenXml()}</Target></VentCalc>");
                sw.Close();
            }
        }

        #endregion

        private void RestoreLogView_Click(object sender, RoutedEventArgs e)
        {
            Settings.ShowLogView = !Settings.ShowLogView;
        }

        private void RestoreToolbar_Click(object sender, RoutedEventArgs e)
        {
            Settings.ShowToolbar = !Settings.ShowToolbar;
        }

        private void Help_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("http://envsafe.cn/c/ventool");
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            new DiaAbout().ShowDialog();
        }

        #region 参数获取

        private void BtnFetchKst_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("http://dees.iepi.com.cn/Explosibility/Query.aspx");
        }

        #endregion

    }
}
